name: Merge to Main branch

on:
  push:
    branches:
    - main
  pull_request:
    branches:
    - main

env:
  AWS_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY }}
  AWS_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_KEY }}
  TF_VAR_vms_mem: 4

jobs: 
  check-code:
    runs-on: ubuntu-latest
    # Use the Bash shell regardless whether the GitHub Actions runner is ubuntu-latest, macos-latest, or windows-latest
    # Set the working directory to vnet for the config files
    # defaults:
    #     run:
    #       shell: bash
    #       working-directory: ./vnet
    steps:
      # Checkout the repository to the GitHub Actions runner
      - name: Checkout
        uses: actions/checkout@v3
      - name: Create IAM token
        id: generation-iam-token
        uses: bigtows/yc-token@latest
        with:
          service-account-token: ${{ secrets.SERVICE_ACCOUNT_TOKEN }}
          type-token: iam
      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v2
        with:
          terraform_version: ${{ secrets.TERRAFORM_VERSION }}
      - name: Terraform Init
        id: init
        env:
          TF_VAR_yc_token: ${{ steps.generation-iam-token.outputs.iam-token }}
          TF_VAR_cloud_id: ${{ secrets.YC_CLOUD_ID}}
          TF_VAR_folder_id: ${{ secrets.YC_FOLDER_ID}}
        run: terraform init -backend-config="access_key=${{ secrets.S3_ACCESS_KEY }}" -backend-config="secret_key=${{ secrets.S3_SECRET_KEY }}"
      - name: Terraform Format
        id: fmt
        run: terraform fmt -check
      - name: Terraform Validate
        id: validate
        # Run even if formatting fails
        if: success() || failure()
        run: terraform validate -no-color
      - name: Terraform Plan
        id: plan
        env:
          TF_VAR_yc_token: ${{ steps.generation-iam-token.outputs.iam-token }}
          TF_VAR_cloud_id: ${{ secrets.YC_CLOUD_ID}}
          TF_VAR_folder_id: ${{ secrets.YC_FOLDER_ID}}
        run: terraform plan -no-color
      - name: Terraform Apply
        id: apply
        env:
          TF_VAR_yc_token: ${{ steps.generation-iam-token.outputs.iam-token }}
          TF_VAR_cloud_id: ${{ secrets.YC_CLOUD_ID}}
          TF_VAR_folder_id: ${{ secrets.YC_FOLDER_ID}}
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: terraform apply -auto-approve